package com.example.thread.d9CompletableFuture2.d5合并多个异步任务allOf和anyOf;

import com.example.thread.d9CompletableFuture2.CommonUtils;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 当给定的多个异步任务中的有任意Future一个完成时，需要执行一些操作，可以使用anyOf方法
 * public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
 * anyOf()返回一个新的CompletableFuture，新的CompletableFutute的结果和cfs中已完成的那个异步任务结果相同
 */
public class d2_anyOfDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            CommonUtils.sleepSecond(2);
            return "Future1的结果";
        });
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            CommonUtils.sleepSecond(4);
            return "Future2的结果";
        });
        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
            CommonUtils.sleepSecond(1);
            return "Future3的结果";
        });

        CompletableFuture<Object> future = CompletableFuture.anyOf(future2, future1, future3);
        Object o = future.get();
        System.out.println(o);

        /**
         * anyOf()方法的返回类型必须是CompletableFuture<Object>
         */
    }
}
